package com.tron.sync.commons;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class ErrorHandlerController {

    /**
     * 处理没有被明确指定处理类的异常信息
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String,Object>> errorHandler(Exception e) {
        //后台处理
        StackTraceElement[] stackTrace = e.getStackTrace();
        StackTraceElement traceElement = stackTrace[0];
        log.error("\"message\":\"{}\"",traceElement.getClassName()+":"+traceElement.getLineNumber()+"--->"+e.getMessage());
        //前端友好提示
        HashMap<String, Object> map = new HashMap<>();
        map.put("message", e.getMessage());
        map.put("code", 3000);
        map.put("state", 500);
        //修改返回头状态码
        return new ResponseEntity<>(map, HttpStatus.I_AM_A_TEAPOT);
    }
}
